package cn.yunyichina.provider.hquery.service.impl;

import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.hquery.thread.InspectDetailRunnable;
import cn.yunyichina.provider.hquery.thread.InspectListAndDetailRunnable;
import cn.yunyichina.provider.hquery.thread.InspectListRunnable;
import cn.yunyichina.provider.hquery.vo.ExaminationVo;
import cn.yunyichina.provider.hquery.vo.InspectListVoResp;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectDetailVo;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectDetailVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectListVo;
import cn.yunyichina.provider.iface.entity.hisiface.examination.InspectListVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2016/12/12 0012.
 * 检验检查功能
 */
@Service("inspectServiceImpl")
public class InspectServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(InspectServiceImpl.class);

    //编写Comparator,根据reportTime对ExamineListVoResponse进行排序
    private final Comparator<InspectListVoResponse> COMPARATOR = new Comparator<InspectListVoResponse>() {
       public int compare(InspectListVoResponse o1, InspectListVoResponse o2) {
           return o1.compareTo(o2);//运用User类的compareTo方法比较两个对象       
       }
    };

    /**
	 * yyt.hquery.inspect.list.get
	 * 检验结果列表和明细查询接口
     */
	public ResponseObject getInspectList(String data,String sessionId,String appId) {
		logger.info("检验结果列表和明细 getInspectList data: "+data);
        ResponseObject response = new ResponseObject();
        	
        ExaminationVo requestVo = JsonUtils.parseObject(data, ExaminationVo.class);
        if (StringUtils.isBlank(requestVo.getHospitalCode())
                ||StringUtils.isBlank(requestVo.getBeginDate())
                ||StringUtils.isBlank(requestVo.getEndDate())){
            response.setResultCodeAndMessage("18002","hospitalCode,beginDate,endDate不能为空");
            return response;
        }
        
        //结果集 检验列表信息
        List<InspectListVoResponse> inspectListVoResponseList = null;
        
        //检验列表查询
        try {
            InspectListVo inspectListVo = new InspectListVo();
            inspectListVo.setHospitalCode(requestVo.getHospitalCode());
            inspectListVo.setBranchCode(requestVo.getBranchCode());
            inspectListVo.setPatCardType(requestVo.getPatCardType());
            inspectListVo.setPatCardNo(requestVo.getPatCardNo());
            inspectListVo.setBeginDate(requestVo.getBeginDate());
            inspectListVo.setEndDate(requestVo.getEndDate());
            inspectListVo.setPatId(requestVo.getPatId());
            logger.info("调用调度中心开始");
            ResCommon<List<InspectListVoResponse>> inspectList  = HisifaceService.getHisifaceClient().getInspectList(inspectListVo);
            logger.info("调用调度中心结束");
            if (!"0".equals(inspectList.getResultCode())){
                logger.info("调用调度中心产生异常"+ inspectList.getResultMessage());
                response.setResultCodeAndMessage("18998", inspectList.getResultMessage());
                return response;
            }
            logger.info("调用调度中心返回 "+JsonUtils.toJsonString(inspectList));
            
            inspectListVoResponseList = inspectList.getResult();
            
        } catch (Exception ex) {
            response.setResultCodeAndMessage("18999","系统异常");
            return  response;
        }

        //检验明细查询
        try {
            InspectDetailVo inspectDetailVo = new InspectDetailVo();
            for(InspectListVoResponse inspectListVoResponse : inspectListVoResponseList){
            	inspectDetailVo.setHospitalCode(requestVo.getHospitalCode());
            	inspectDetailVo.setBranchCode(requestVo.getBranchCode());
            	inspectDetailVo.setInspectId(inspectListVoResponse.getInspectId());
                logger.info("调用调度中心开始");
                ResCommon<List<InspectDetailVoResponse>> inspectDetails  = HisifaceService.getHisifaceClient().getInspectDetail(inspectDetailVo);
                logger.info("调用调度中心结束");
                if (!"0".equals(inspectDetails.getResultCode())){
                    logger.info("调用调度中心产生异常"+ inspectDetails.getResultMessage());
                    response.setResultCodeAndMessage("18998", inspectDetails.getResultMessage());
                    return response;
                }
                logger.info("调用调度中心返回 "+JsonUtils.toJsonString(inspectDetails));
                inspectListVoResponse.setInspectDetails(inspectDetails.getResult());
            }

        } catch (Exception ex) {
            response.setResultCodeAndMessage("18999","系统异常");
            return  response;
        }
        
        List<InspectListVoResponse> emptyReportimeList = new ArrayList<InspectListVoResponse>();
        List<InspectListVoResponse> notEmptyReportimeList = new ArrayList<InspectListVoResponse>();

        for(InspectListVoResponse u : inspectListVoResponseList){
            if("".equals(u.getReportTime()) || u.getReportTime() == null){
                emptyReportimeList.add(u);
            } else {
                notEmptyReportimeList.add(u);
            }
        }
        //用我们写好的Comparator对notEmptyReportimeList进行reprotTime日期升序排序
        Collections.sort(notEmptyReportimeList, COMPARATOR);
        inspectListVoResponseList.clear();
        inspectListVoResponseList.addAll(notEmptyReportimeList);
        inspectListVoResponseList.addAll(emptyReportimeList);
        
        if(CollectionUtils.isNotEmpty(inspectListVoResponseList)){
        	//检查列表和明细入库
			requestVo.setAppId(appId);
			logger.info("getInspectList requestVo={}",new Object[]{JsonUtils.toJsonString(requestVo)});
        	Thread  getInspectListAndDetailThread = new Thread(new InspectListAndDetailRunnable(inspectListVoResponseList,requestVo));
        	getInspectListAndDetailThread.start();
        }
        
        response.setResultCodeAndMessageAndResult("0","成功",inspectListVoResponseList);
        logger.info("【检验结果列表和明细查询】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
	}
	
	/*
	    检验结果列表查询接口
	*/
	public ResponseObject listInspect(String data,String sessionId,String appId) {
		logger.info("检验结果列表 inspectList data: "+data);
	    ResponseObject response = new ResponseObject();
	    	
	    ExaminationVo requestVo = JsonUtils.parseObject(data, ExaminationVo.class);
	    if (StringUtils.isBlank(requestVo.getHospitalCode())
	            ||StringUtils.isBlank(requestVo.getBeginDate())
	            ||StringUtils.isBlank(requestVo.getEndDate())){
	        response.setResultCodeAndMessage("18002","hospitalCode,beginDate,endDate不能为空");
	        return response;
	    }
	    
	    //结果集 检验列表信息
	    List<InspectListVoResponse> inspectListVoResponseList = null;
	    
	    //检验列表查询
	    try {
	        InspectListVo inspectListVo = new InspectListVo();
	        inspectListVo.setHospitalCode(requestVo.getHospitalCode());
	        inspectListVo.setBranchCode(requestVo.getBranchCode());
	        inspectListVo.setPatCardType(requestVo.getPatCardType());
	        inspectListVo.setPatCardNo(requestVo.getPatCardNo());
	        inspectListVo.setBeginDate(requestVo.getBeginDate());
	        inspectListVo.setEndDate(requestVo.getEndDate());
	        inspectListVo.setPatId(requestVo.getPatId());
	        inspectListVo.setAdmissionNo(requestVo.getAdmissionNo());
	        logger.info("调用调度中心开始");
	        ResCommon<List<InspectListVoResponse>> inspectList  = HisifaceService.getHisifaceClient().getInspectList(inspectListVo);
	        logger.info("调用调度中心结束");
	        if (!"0".equals(inspectList.getResultCode())){
	            logger.info("调用调度中心产生异常"+ inspectList.getResultMessage());
	            response.setResultCodeAndMessage("18998", inspectList.getResultMessage());
	            return response;
	        }
	        logger.info("调用调度中心返回 "+JsonUtils.toJsonString(inspectList));
	        
	        inspectListVoResponseList = inspectList.getResult();
	        
	    } catch (Exception ex) {
	        response.setResultCodeAndMessage("18999","系统异常");
	        return  response;
	    }
	
	    List<InspectListVoResponse> emptyReportimeList = new ArrayList<InspectListVoResponse>();
	    List<InspectListVoResponse> notEmptyReportimeList = new ArrayList<InspectListVoResponse>();
	
	    for(InspectListVoResponse u : inspectListVoResponseList){
	        if("".equals(u.getReportTime()) || u.getReportTime() == null){
	            emptyReportimeList.add(u);
	        } else {
	            notEmptyReportimeList.add(u);
	        }
	    }
	    //用我们写好的Comparator对notEmptyReportimeList进行reprotTime日期升序排序
	    Collections.sort(notEmptyReportimeList, COMPARATOR);
	    inspectListVoResponseList.clear();
	    inspectListVoResponseList.addAll(notEmptyReportimeList);
	    inspectListVoResponseList.addAll(emptyReportimeList);
	    
	    List<InspectListVoResp> inspectListVoRespList = new ArrayList<InspectListVoResp>();
	    if(CollectionUtils.isNotEmpty(inspectListVoResponseList)){
	    	
	    	InspectListVoResp inspectListVoResp = null;
	    	for(InspectListVoResponse inspectListVoResponse:inspectListVoResponseList){
	    		inspectListVoResp = new InspectListVoResp();
	    		inspectListVoResp.setInspectId(inspectListVoResponse.getInspectId());
	    		inspectListVoResp.setInspectName(inspectListVoResponse.getInspectName());
	    		inspectListVoResp.setOrderDoctorCode(inspectListVoResponse.getDoctorCode());
	    		inspectListVoResp.setOrderDoctorName(inspectListVoResponse.getDoctorName());
            	inspectListVoResp.setOrderDeptName(inspectListVoResponse.getDeptName());
            	inspectListVoResp.setOrderTime(inspectListVoResponse.getInspectTime());
            	inspectListVoResp.setInspectDoctorName(inspectListVoResponse.getInspectDoctor());
            	inspectListVoResp.setInspectTime(inspectListVoResponse.getProvingTime());
            	inspectListVoResp.setVerifyDoctorName(inspectListVoResponse.getVerifyDoctor());
            	inspectListVoResp.setVerifyTime(inspectListVoResponse.getVerifyTime());
            	inspectListVoResp.setReportTime(inspectListVoResponse.getReportTime());
            	inspectListVoResp.setFileAddress(inspectListVoResponse.getFileAddress());
            	inspectListVoResp.setClinicalComment(inspectListVoResponse.getClinicalComment());
            	inspectListVoResp.setDetectionResult(inspectListVoResponse.getDetectionResult());
            	inspectListVoResp.setReportContents(inspectListVoResponse.getReportContents());

            	inspectListVoRespList.add(inspectListVoResp);
            }
			requestVo.setAppId(appId);
	    	//检查列表入库
			logger.info("listInspect requevo ={}",new Object[]{JsonUtils.toJsonString(requestVo)});
	    	Thread  listInspectThread = new Thread(new InspectListRunnable(inspectListVoResponseList,requestVo));
	    	listInspectThread.start();
	    }
	    
	    response.setResultCodeAndMessageAndResult("0","成功",inspectListVoRespList);
	    logger.info("【检验结果列表查询】结束, 返回结果=" + JsonUtils.toJsonString(response));
	    return response;
	}
		
	
    /*
              检验结果明细查询接口
	*/
	public ResponseObject listInspectDetail(String data,String sessionId,String appId) {
		logger.info("检验结果明细 listInspectDetail data: "+data);
	    ResponseObject response = new ResponseObject();
	    	
	    ExaminationVo requestVo = JsonUtils.parseObject(data, ExaminationVo.class);
	    if (StringUtils.isBlank(requestVo.getHospitalCode())
	            ||StringUtils.isBlank(requestVo.getInspectId())){
	        response.setResultCodeAndMessage("18002","hospitalCode,inspectId不能为空");
	        return response;
	    }
	    
	    //结果集 检验列表信息
	    List<InspectDetailVoResponse> inspectDetailVoResponseList = null;
	    
	    //检验明细查询
	    try {
	        InspectDetailVo inspectDetailVo = new InspectDetailVo();
        	inspectDetailVo.setHospitalCode(requestVo.getHospitalCode());
        	inspectDetailVo.setBranchCode(requestVo.getBranchCode());
        	inspectDetailVo.setInspectId(requestVo.getInspectId());
            logger.info("调用调度中心开始");
            ResCommon<List<InspectDetailVoResponse>> inspectDetails  = HisifaceService.getHisifaceClient().getInspectDetail(inspectDetailVo);
            logger.info("调用调度中心结束");
            if (!"0".equals(inspectDetails.getResultCode())){
                logger.info("调用调度中心产生异常"+ inspectDetails.getResultMessage());
                response.setResultCodeAndMessage("18998", inspectDetails.getResultMessage());
                return response;
            }
            logger.info("调用调度中心返回 "+JsonUtils.toJsonString(inspectDetails));
            inspectDetailVoResponseList = inspectDetails.getResult();
	
	    } catch (Exception ex) {
	        response.setResultCodeAndMessage("18999","系统异常");
	        return  response;
	    }
	    
	    if(CollectionUtils.isNotEmpty(inspectDetailVoResponseList)){
	    	//检查列表入库
			requestVo.setAppId(appId);
			logger.info("listInspectDetail requestVo={}",new Object[]{JsonUtils.toJsonString(requestVo)});
	    	Thread  inspectDetailThread = new Thread(new InspectDetailRunnable(inspectDetailVoResponseList,requestVo));
	    	inspectDetailThread.start();
	    }
	    
	    response.setResultCodeAndMessageAndResult("0","成功",inspectDetailVoResponseList);
	    logger.info("【检验结果明细查询】结束, 返回结果=" + JsonUtils.toJsonString(response));
	    return response;
	}
}
